import dayjs from "dayjs";
import { usePublicHooks } from "../hooks";
import { reactive, ref, onMounted, h } from "vue";
import { message } from "@/utils/message";
import { addDialog } from '@/components/ReDialog'
import { ElMessageBox } from 'element-plus'
import { type FormItemProps } from "./types";
import { type PaginationProps } from "@pureadmin/table";
import elForm from '../form.vue'
import { ElTree } from 'element-plus';
import { $t } from "@/plugins/i18n";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";

import { callList, addCall, updateCall, delCall, GetAllCall } from '@/utils/api/BasicManagement/calling'
import { GetAllStation } from '@/utils/api/dispatch/station'
import { GetStorePlaceList } from '@/utils/api/BasicManagement/locations'

export function useDept() {
    const { locale } = useTranslationLang(); // 获取语言
    const form = reactive({
        name: "",
        pageNumber: 0,
        pageSize: 10,
        sortName: "createtime",
        sortType: 0
    });

    const formRef = ref();
    const dataList = ref([]);
    const loading = ref(true);
    const { tagStyle } = usePublicHooks();
    const pagination = reactive<PaginationProps>({
        total: 0,
        pageSize: 10,
        currentPage: 1,
        background: true
    });
    // 状态select
    const statusSelect = ref([
        { value: 1, label: '启用' },
        { value: 0, label: '禁用' },
    ])
    // 站点select
    let stationSelect = ref([])
    // 关联网关
    let affiliationSelect = ref([])

    const columns = ref<TableColumnList>([
        {
            label: $t('calling.deviceName'),
            prop: "name",
            width: 150,
            align: "left",
            sortable: true
        },
        {
            label: $t('calling.ipAddress'),
            prop: "ip",
            width: 150,
            align: "left",
        },
        {
            label: $t('calling.communicationPort'),
            prop: "port",
            width: 170,
            align: "left",
        },
        {
            label: $t('calling.deviceNumber'),
            prop: "number",
            width: 150,
            align: "left",
            sortable: true
        },
        {
            label: $t('calling.status'),
            prop: "status",
            width: 110,
            sortable: true,
            cellRenderer: ({ row, props }) => (
                <el-tag size={props.size} style={tagStyle.value(row.status)}>
                    {row.status === 1 ? $t('calling.enable') : $t('calling.disable')}
                </el-tag>
            )
        },
        {
            label: $t('calling.remarks'),
            prop: "note",
            align: "left",
            sortable: true
        },
        {
            label: $t('calling.operation'),
            fixed: "right",
            width: 200,
            slot: "operation"
        }
    ])

    function tableReloading() {
        columns.value = [
            {
                label: $t('calling.deviceName'),
                prop: "name",
                width: 150,
                align: "left",
                sortable: true
            },
            {
                label: $t('calling.ipAddress'),
                prop: "ip",
                width: 150,
                align: "left",
            },
            {
                label: $t('calling.communicationPort'),
                prop: "port",
                width: 170,
                align: "left",
            },
            {
                label: $t('calling.deviceNumber'),
                prop: "number",
                width: 150,
                align: "left",
                sortable: true
            },
            {
                label: $t('calling.status'),
                prop: "status",
                width: 110,
                sortable: true,
                cellRenderer: ({ row, props }) => (
                    <el-tag size={props.size} style={tagStyle.value(row.status)}>
                        {row.status === 1 ? $t('calling.enable') : $t('calling.disable')}
                    </el-tag>
                )
            },
            {
                label: $t('calling.remarks'),
                prop: "note",
                align: "left",
                sortable: true
            },
            {
                label: $t('calling.operation'),
                fixed: "right",
                width: 200,
                slot: "operation"
            }
        ]
    }

    async function onSearch() {
        loading.value = true;
        const { Content } = await callList(form);
        let newData = Content.Results;
        dataList.value = newData;
        pagination.total = Content.TotalCount;
        pagination.pageSize = Content.PageSize;
        pagination.currentPage = Content.PageNumber + 1;

        setTimeout(() => {
            loading.value = false;
        }, 500);
    }

    // 重置
    function resetForm(formEl) {
        if (!formEl) return;
        formEl.resetFields();
        onSearch();
    }

    function openDialog(title = "新增", row?: FormItemProps) {
        const newTitle = title === "新增" ? $t('calling.addCallDevice') : $t('calling.edit')
        addDialog({
            title: newTitle,
            props: {
                formInline: {
                    code: row?.code ?? "",
                    name: row?.name ?? "",
                    ip: row?.ip ?? "",
                    port: row?.port ?? null,
                    status: row?.status ?? 1,
                    number: row?.number ?? "",
                    note: row?.note ?? "",
                    callboxList: row?.callboxList ?? [{ status: 1 }]
                },
                statusSelect: statusSelect.value || [],
                stationSelect: stationSelect.value || [],
                affiliationSelect: affiliationSelect.value || [],
            },
            width: "45%",
            draggable: true,
            fullscreenIcon: true,
            closeOnClickModal: false,
            //@ts-ignore
            contentRenderer: () => h(elForm, { ref: formRef }),
            beforeSure: (done, { options }) => {
                const FormRef = formRef.value.getRef();
                const curData = options.props.formInline as FormItemProps;
                function chores() {
                    message($t('form.operationSuccessful'), {
                        type: "success"
                    });
                    done(); // 关闭弹框
                    onSearch(); // 刷新表格数据
                }
                FormRef.validate(valid => {
                    if (valid) {
                        console.log("curData", curData);
                        // 表单规则校验通过
                        if (title === "新增") {
                            //@ts-ignore
                            addCall(curData).then(res => {
                                if (res.Code === 0) chores();
                            })
                        } else {
                            let data = Object.assign(curData, { id: row.id })
                            //@ts-ignore
                            updateCall(data).then(res => {
                                if (res.Code === 0) chores();
                            })
                        }
                    }
                });
            }
        })
    }

    // 删除
    function handleDelete(row) {
        ElMessageBox.confirm(
            $t('form.confirmDeletion'),
            $t('form.prompt'),
            {
                confirmButtonText: $t('form.confirm'),
                cancelButtonText: $t('form.cancel'),
                type: 'warning',
                center: true,
            }
        ).then(() => {
            delCall(row.id).then(res => {
                if (res.Code === 0) {
                    message($t('form.operationSuccessful'), { type: "success" });
                    onSearch();
                }
            })
        }).catch(() => { })
    }

    function handleSizeChange(val: number) {
        form.pageSize = val
        onSearch()
    }

    function handleCurrentChange(val: number) {
        form.pageNumber = val - 1
        onSearch()
    }

    onMounted(async () => {
        onSearch()
        // 关联工位
        let { Content: store } = await GetStorePlaceList({})
        stationSelect.value = store
    })

    return {
        columns,
        loading,
        dataList,
        openDialog,
        handleDelete,
        form,
        onSearch,
        resetForm,
        pagination,
        handleSizeChange,
        handleCurrentChange,
        statusSelect,
        tableReloading
    }
}